package com.jrx.anytxn.param.service.rights.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.common.uitl.BeanMapping;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.common.uitl.StringUtils;
import com.jrx.anytxn.i18n.response.TxnPage;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.constant.ErrorMsgConstant;
import com.jrx.anytxn.param.entity.PrActivityInfoReq;
import com.jrx.anytxn.param.entity.PrActivityInfoRes;
import com.jrx.anytxn.param.entity.PrActivityInfo;
import com.jrx.anytxn.param.enums.EnableTagEnum;
import com.jrx.anytxn.param.mapper.ext.ExtPrActivityInfoMapper;
import com.jrx.anytxn.param.service.rights.IPrActivityInfoService;
import com.jrx.anytxn.param.service.rights.IPrRightsAndInterestsService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;

/**
 * ClassName PrActivityInfoServiceImpl
 *
 * @author lujianyou
 * @version 1.0
 * @description 活动信息接口实现类
 * @date 2021/7/2 23:38
 **/
@Service
public class PrActivityInfoServiceImpl implements IPrActivityInfoService {
    private static final Logger logger = LoggerFactory.getLogger(PrActivityInfoServiceImpl.class);

    @Autowired
    private ExtPrActivityInfoMapper extPrActivityInfoMapper;

    @Autowired
    private ISegmentService segmentService;

    @Autowired
    IPrRightsAndInterestsService rightsAndInterestsService;

    /**
     * 根据机构号获取活动列表
     *
     * @param tenantId
     * @return
     */
    @Override
    public List<PrActivityInfo> listByTenantId(String tenantId) {
        return extPrActivityInfoMapper.selectByTenantId(tenantId);
    }

    /**
     * 根基租户号、活动号 获取活动信息
     *
     * @param tenantId
     * @param activityId
     * @return
     */
    @Override
    public PrActivityInfo getByTenantIdAndActivityId(String tenantId, String activityId) {
        return extPrActivityInfoMapper.selectByTenantIdAndActivityId(tenantId, activityId);
    }

    /**
     * 校验活动的有效性
     * @param tenantId
     * @param activityId
     */
    @Override
    public PrActivityInfo checkActivity(String tenantId, String activityId) throws TxnBizException {
        PrActivityInfo activityInfo = getByTenantIdAndActivityId(tenantId, activityId);
        if(activityInfo == null){
            throw new TxnBizException(TxnRespCode.ACTIVITY_NOT_EXIST);
        }
        String enableTag = activityInfo.getEnableTag();
        if(EnableTagEnum.TO_ABLE.getCode().equals(enableTag)){
            throw new TxnBizException(TxnRespCode.ACTIVITY_TO_ABLE);
        }
        if(EnableTagEnum.DISABLED.getCode().equals(enableTag)){
            throw new TxnBizException(TxnRespCode.ACTIVITY_DISABLED);
        }
        if (Integer.valueOf(0).equals(activityInfo.getStoreQuantity())) {
            throw new TxnBizException(TxnRespCode.ACTIVITY_QUANTITY_ZERO);
        }
        //校验活动是否在生效期间内
        try {
            String effectiveDateStr = activityInfo.getEffectiveDate();
            String expireDateStr = activityInfo.getExpireDate();
            //设置日期格式
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Date currentDate = new Date();
            //生效日期
            Date effectiveDate = df.parse(effectiveDateStr);
            //失效日期
            Date expireDate = df.parse(expireDateStr);
            if (currentDate.before(effectiveDate)){
                throw new TxnBizException(TxnRespCode.ACTIVITY_TO_ABLE);
            }
            if(currentDate.after(expireDate)){
                throw new TxnBizException(TxnRespCode.ACTIVITY_DISABLED);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return activityInfo;
    }

	/**
	 * 校验活动的所有属性的有效性
	 * @param tenantId
	 * @param activityId
	 * @return
	 * @throws TxnBizException
	 */
	@Override
	public PrActivityInfo checkAllActivityInfo(String tenantId, String activityId,String productCode) throws TxnBizException {
	    PrActivityInfo activityInfo = getByTenantIdAndActivityId(tenantId, activityId);
	    if(activityInfo == null){
	        logger.info("根据租户号:{}、活动号:{}查询活动信息，无记录", tenantId,activityId);
	        throw new TxnBizException(TxnRespCode.ACTIVITY_NOT_EXIST);
	    }
	    String enableTag = activityInfo.getEnableTag();
	    if(EnableTagEnum.TO_ABLE.getCode().equals(enableTag)){
	        throw new TxnBizException(TxnRespCode.ACTIVITY_TO_ABLE);
	    }
	    if(EnableTagEnum.DISABLED.getCode().equals(enableTag)){
	        throw new TxnBizException(TxnRespCode.ACTIVITY_DISABLED);
	    }
	    if(activityInfo.getStoreQuantity()<=0){
	        throw new TxnBizException(TxnRespCode.ACTIVITY_STOCK_DEFICIENT);
	    }
	    String effectiveDate = activityInfo.getEffectiveDate();
	    String expireDate = activityInfo.getExpireDate();
	    LocalDate now = LocalDate.now();
	    if(now.isBefore(DateUtils.parse(effectiveDate))){
	        throw new TxnBizException(TxnRespCode.ACTIVITY_NOT_BEGIN);
	    }
	    if(now.isAfter(DateUtils.parse(expireDate))){
	        throw new TxnBizException(TxnRespCode.ACTIVITY_EXPIRE);
	    }
        String rightsIds = activityInfo.getRightsId();
        String[] rightsIdArr = rightsIds.split(",");
        for (int i = 0; i < rightsIdArr.length; i++) {
            rightsAndInterestsService.checkRightsAndInterests(tenantId,rightsIdArr[i],productCode);
        }

	    return activityInfo;
	}

    /**
     * 更新
     *
     * @param activityInfo
     * @return
     */
    @Override
    public int updateByPrimaryKeySelective(PrActivityInfo activityInfo) {
        return extPrActivityInfoMapper.updateByPrimaryKeySelective(activityInfo);
    }


    @Override
    public PrActivityInfoRes addPrActivityInfoRes(PrActivityInfoReq prActivityInfoReq) throws TxnException{

        PrActivityInfo table = extPrActivityInfoMapper.selectByTenantIdAndActivityId(
                prActivityInfoReq.getTenantId(),prActivityInfoReq.getActivityId());
        if (table != null) {
            logger.error(TxnRespCode.DATA_EXISTS.getMsg());
            throw new TxnBizException(TxnRespCode.DATA_EXISTS.getMsg());
        }
        PrActivityInfo prActivityInfo = BeanMapping.copy(prActivityInfoReq, PrActivityInfo.class);
        try {
            prActivityInfo.setId(segmentService.getId(Constant.PR_ACTIVITY_INFO_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误",e);
            throw new TxnBizException(ErrorMsgConstant.ERROR_ID);
        }
        prActivityInfo.setRecordVersionNumber(Constant.VERSION_NUMBER);
        extPrActivityInfoMapper.insertSelective(prActivityInfo);
        return BeanMapping.copy(prActivityInfoReq, PrActivityInfoRes.class);
    }


    //@CacheEvict(key="'rights_'+#prActivityInfoReq.tenantId+'_'+#prActivityInfoReq.activityId")
    @Override
    public PrActivityInfoRes modifyPrActivityInfo(PrActivityInfoReq prActivityInfoReq) throws TxnBizException {
        PrActivityInfo table = extPrActivityInfoMapper.selectByTenantIdAndActivityId(
                prActivityInfoReq.getTenantId(),prActivityInfoReq.getActivityId());
        if (table == null) {
            logger.error(TxnRespCode.NO_DATA.getMsg());
            throw new TxnBizException(TxnRespCode.NO_DATA.getMsg());
        }

        PrActivityInfo prShareProfitTable = BeanMapping.copy(prActivityInfoReq, PrActivityInfo.class);
        // 更新
        extPrActivityInfoMapper.updateByTenantIdAndActivityId(prShareProfitTable);
        return BeanMapping.copy(prActivityInfoReq, PrActivityInfoRes.class);
    }

    @Override
    public PrActivityInfoRes getByTenIdAndActivityId(String tenantId, String activityId) throws TxnException {
        if (StringUtils.isBlank(tenantId) || StringUtils.isBlank(activityId)) {
            logger.error("商户ID或活动ID为空");
            throw new TxnBizException(TxnRespCode.NOT_EMPTY.getMsg());
        }

        PrActivityInfo prActivityInfo = extPrActivityInfoMapper.selectByTenantIdAndActivityId(tenantId,activityId);
        if (null == prActivityInfo) {
            logger.error("未查到活动参数信息");
            throw new TxnBizException(TxnRespCode.NO_DATA.getMsg());
        }
        return BeanMapping.copy(prActivityInfo, PrActivityInfoRes.class);
    }


    @Override
    public TxnPage<PrActivityInfoRes> findAllPageByCondition(Integer pageNum, Integer pageSize, PrActivityInfoReq req) throws TxnException {
        Page<PrActivityInfoRes> page = PageHelper.startPage(pageNum, pageSize, Constant.ORDER_BY_SORT);
        List<PrActivityInfo> tableList = extPrActivityInfoMapper.selectByPrActivityInfoReq(req);
        if (CollectionUtils.isEmpty(tableList)) {
            logger.error(TxnRespCode.NO_DATA.getMsg());
            throw new TxnBizException(TxnRespCode.NO_DATA.getMsg());
        }
        List<PrActivityInfoRes> res = BeanMapping.copyList(tableList, PrActivityInfoRes.class);
        return new TxnPage<>(pageNum, pageSize, page.getTotal(), res);

    }

    //@CacheEvict(key="'rights_'+#tenantId+'_'+#activityId")
    @Override
    public Boolean removeByTenantIdAndRightsId(String tenantId, String activityId) throws TxnBizException {
        if (StringUtils.isBlank(tenantId) || StringUtils.isBlank(activityId)) {
            logger.error("租户id或活动id不可为空");
            throw new TxnBizException(TxnRespCode.NOT_EMPTY.getMsg());
        }
        int i = extPrActivityInfoMapper.deleteByTenantIdAndActivityId(tenantId,activityId);
        return i > 0;
    }

}
